import React, { useEffect, } from "react";
import { deviceStore, userStore, Storage, RecordKeys } from "~/store";
import { getDeviceTypeList, getUserBoundDeviceListApi } from "~/api/deviceApi";
import { useFocusEffect } from "@react-navigation/native";
// 获取整个设备类型
export const useDeviceType = () => {
    useEffect(() => {
        if (userStore.me.token) {
            getDeviceTypeList().then(res => {
                const result = res.list
                deviceStore.setDeviceTypeList(result)
            }).catch(err => {

            })
        }
    }, [userStore.me.token]);
}

// 获取用户已绑定的设备列表
export const useBindDeviceList = () => {
    useFocusEffect(
        React.useCallback(() => {
            if (!userStore.me.token) return
            getUserBoundDeviceListApi().then(async res => {
                if (res.status == 1) {
                    const result = res.device_list
                    userStore.userBindDeviceData = result
                    const userDeviceYY01Data = Array.isArray(res.device_list)
                        ? res.device_list.filter(device =>
                            ["YY01", "YY08"].includes(device.device_code?.trim()?.toUpperCase())
                        )
                        : [];
                    const updatedDevices = userDeviceYY01Data.map(device => ({
                        ...device,
                        num: device.device_sn.slice(-3)
                    }));
                    userStore.userDeviceYY01Data = updatedDevices
                    if (result.length > 0) {
                        const autoSn = await Storage.getItem(RecordKeys.autoConnectDeviceSn) || ''
                        const deviceInfo = result.find(item => item.device_sn == autoSn)
                        if (deviceInfo) {
                            userStore.signAutoConnectDevice(deviceInfo.device_sn)
                        } else {
                            userStore.signAutoConnectDevice('')
                        }
                    }
                } else {
                    userStore.userBindDeviceData = []
                    userStore.signAutoConnectDevice('')
                }
            }).catch(err => {

            })
        }, [userStore.me.token]),
    );

}